const GoodsService = require('../../../services/goods');

Page({
    data: {
        // 分类树数据
        items: [],
        mainActiveIndex: 0,
        activeId: null,
        
        // 商品列表数据
        goodsList: [],
        loading: false,
        loadingMore: false,
        hasMore: true,
        page: 1,
        limit: 10,
        
        // 搜索相关
        searchKeyword: '',
        
        // 当前选中的分类
        currentCatId: 0,
        currentSubCatId: 0,
        
        // 二级分类tabs相关
        subCatsTabs: [],
        activeTabIndex: 0,
        scrollLeft: 0,
        lineLeft: 0
    },

    onLoad() {
        this.loadCategories();
        this.loadGoodsList();
    },

    onReady() {
        // 页面渲染完成后初始化指示线位置
        this.updateTabLinePosition(0);
    },

    /**
     * 加载商品分类
     */
    async loadCategories() {
        try {
            const result = await GoodsService.getCategories();
            if (result.success && result.data && result.data.length > 0) {
                this.setData({
                    items: result.data
                });
                // 初始化第一个分类的二级分类tabs
                await this.updateSubCatsTabs(0);
            } else {
                // 如果没有分类数据，设置默认分类
                this.setData({
                    items: [
                        {
                            id: 0,
                            text: '全部商品',
                            children: []
                        }
                    ]
                });
                await this.updateSubCatsTabs(0);
            }
        } catch (error) {
            console.error('加载分类失败:', error);
            // 设置默认分类
            this.setData({
                items: [
                    {
                        id: 0,
                        text: '全部商品',
                        children: []
                    }
                ]
            });
            await this.updateSubCatsTabs(0);
        }
    },

    /**
     * 更新二级分类tabs
     */
    async updateSubCatsTabs(mainIndex) {
        const category = this.data.items[mainIndex];
        let subCatsTabs = [];
        
        // 添加"全部"选项
        subCatsTabs.push({
            id: 0,
            title: '全部',
            name: 'all'
        });
        
        // 如果有选中的分类，从服务器获取二级分类
        if (category && category.id > 0) {
            try {
                const result = await GoodsService.getSubCategories(category.id);
                if (result.success && result.data && result.data.length > 0) {
                    // 添加二级分类
                    result.data.forEach(child => {
                        subCatsTabs.push({
                            id: child.id,
                            title: child.text,
                            name: `sub_${child.id}`
                        });
                    });
                }
            } catch (error) {
                console.error('获取二级分类失败:', error);
            }
        }
        
        this.setData({
            subCatsTabs,
            activeTabIndex: 0,
            currentSubCatId: 0
        }, () => {
            // 更新完成后重新计算指示线位置
            this.updateTabLinePosition(0);
        });
    },

    /**
     * 自定义tab点击事件
     */
    onTabClick(event) {
        const { index } = event.currentTarget.dataset;
        const subCat = this.data.subCatsTabs[index];
        
        this.setData({
            activeTabIndex: index,
            currentSubCatId: subCat.id,
            page: 1,
            goodsList: []
        });
        
        // 计算指示线位置和滚动位置
        this.updateTabLinePosition(index);
        
        this.loadGoodsList();
    },

    /**
     * 更新tab指示线位置
     */
    updateTabLinePosition(activeIndex) {
        const query = wx.createSelectorQuery();
        query.select('.tab-item').boundingClientRect();
        query.exec((res) => {
            if (res && res.length > 0) {
                const activeTab = res[activeIndex];
                const containerLeft = res[0].left;
                const lineLeft = activeTab.left - containerLeft + activeTab.width / 2 - 20; // 20rpx是线的宽度的一半
                
                this.setData({
                    lineLeft: lineLeft
                });
            }
        });
    },

    /**
     * 加载商品列表
     */
    async loadGoodsList(isLoadMore = false) {
        if (this.data.loading && !isLoadMore) return;
        
        this.setData({
            loading: !isLoadMore,
            loadingMore: isLoadMore
        });

        try {
            const params = {
                page: this.data.page,
                limit: this.data.limit,
                cat_id: this.data.currentCatId || 0,
                sub_cat_id: this.data.currentSubCatId || 0
            };

            const result = await GoodsService.getGoodsList(params);
            
            if (result.success) {
                const newGoodsList = isLoadMore 
                    ? [...this.data.goodsList, ...result.data.list]
                    : result.data.list;
                
                this.setData({
                    goodsList: newGoodsList,
                    hasMore: result.data.list.length === this.data.limit,
                    loading: false,
                    loadingMore: false
                });
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                });
                this.setData({
                    loading: false,
                    loadingMore: false
                });
            }
        } catch (error) {
            wx.showToast({
                title: '加载商品列表失败',
                icon: 'none'
            });
            this.setData({
                loading: false,
                loadingMore: false
            });
        }
    },

    /**
     * 点击分类导航
     */
    async onClickNav(event) {
        const { index } = event.detail;
        const category = this.data.items[index];
        
        this.setData({
            mainActiveIndex: index,
            activeId: null,
            currentCatId: category.id,
            currentSubCatId: 0,
            page: 1,
            goodsList: []
        });
        
        // 更新二级分类tabs
        await this.updateSubCatsTabs(index);
        
        this.loadGoodsList();
    },

    /**
     * 点击子分类
     */
    onClickItem(event) {
        const { id } = event.detail;
        
        this.setData({
            activeId: id,
            currentSubCatId: id,
            page: 1,
            goodsList: []
        });
        
        this.loadGoodsList();
    },

    /**
     * 搜索框内容变化
     */
    onSearchChange(event) {
        this.setData({
            searchKeyword: event.detail
        });
    },

    /**
     * 搜索商品
     */
    async onSearch() {
        if (!this.data.searchKeyword.trim()) {
            this.loadGoodsList();
            return;
        }

        this.setData({
            loading: true,
            page: 1,
            goodsList: []
        });

        try {
            const result = await GoodsService.searchGoods({
                keyword: this.data.searchKeyword,
                page: 1,
                limit: this.data.limit
            });

            if (result.success) {
                this.setData({
                    goodsList: result.data,
                    hasMore: result.data.length === this.data.limit,
                    loading: false
                });
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                });
                this.setData({
                    loading: false
                });
            }
        } catch (error) {
            wx.showToast({
                title: '搜索失败',
                icon: 'none'
            });
            this.setData({
                loading: false
            });
        }
    },

    /**
     * 加载更多商品
     */
    loadMore() {
        if (this.data.loadingMore || !this.data.hasMore) return;
        
        this.setData({
            page: this.data.page + 1
        });
        
        this.loadGoodsList(true);
    },

    /**
     * 点击商品
     */
    onGoodsClick(event) {
        const { id } = event.currentTarget.dataset;
        
        // 跳转到商品详情页
        wx.navigateTo({
            url: `/store/pages/goods/detail?id=${id}`
        });
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh() {
        this.setData({
            page: 1,
            goodsList: []
        });
        
        this.loadGoodsList().then(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 上拉加载更多
     */
    onReachBottom() {
        if (this.data.hasMore && !this.data.loading) {
            this.loadMore();
        }
    }
});